package com.xioz.android;
/**
 * GameTimer class
 * used to clock or time a game
 * 
 * @author Zong Xiong
 */
public class GameTimer {
	
/***************************************************
 * Fields
 ***************************************************/
	
	// stores time
	private long timeElapsed = 0;
	// stores previous time of system check
	private long previousUpdateTime = 0;
	// if timer is on or off
	private boolean isRunning = false;
	// direction timer is counting
	private boolean isCountingUp = true;
	

/***************************************************
 * Public Methods
 ***************************************************/
	
	/**
	 * Default Constructor
	 * creates a blank timer
	 */
	public GameTimer() {
	}

	/**
	 * setRunning
	 * turns on or off the timer
	 * 
	 * @param play, input to turn timer on
	 */
	public void setRunning(boolean play) {
		isRunning = play;
		previousUpdateTime = System.currentTimeMillis();
	}
	
	/**
	 * reset
	 * resets timer back to 0.
	 * Note: doesn't turn off timer
	 */
	public void reset() {
		timeElapsed = 0;
	}
	
	/**
	 * updateTimer
	 * updates the timer only if the timer is on
	 */
	public void updateTimer() {
		// check if timer is on
		if (isRunning) {
			// if on we load the current time into a variable, so that
			// all checks are done to same time, and check the direction
			// depending on that direction we add or subtract to the timer
			long updateTime = System.currentTimeMillis();
			if (isCountingUp ) {
				timeElapsed += updateTime - previousUpdateTime;
			}
			else {
				timeElapsed -= updateTime - previousUpdateTime;
				if (timeElapsed <= 0) {
					isRunning = false;
					timeElapsed = 0;
				}
			}
			//update previous time
			previousUpdateTime = updateTime;
		}
	}
	
	/**
	 * setTime
	 * set the timer to a time
	 * 
	 * @param inTime, time to set to in milliseconds
	 */
	public void setTime(long inTime) {
		timeElapsed = inTime;
	}
	
	/**
	 * getTime
	 * retrieves current time on timer
	 * 
	 * @return time on timer in milliseconds
	 */
	public long getTime() {
		return timeElapsed;
	}
	
	/**
	 * printTime
	 * prints current time on timer in a format of S.XX, such that S is seconds
	 * 
	 * @return string of printed time in format
	 */
	public String printTime() {
		return new String(timeElapsed/1000 + "." + (timeElapsed/100)%10);
	}
	
	/**
	 * setCountUp
	 * set the direction of counting
	 * 
	 * @param direction, true for counting up - false for counting downs
	 */
	public void setCountUp(boolean direction) {
		isCountingUp = direction;
	}
}
